package org.github.choviwu.example.common.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.github.choviwu.example.common.util.JwtUtil;
import org.github.choviwu.example.common.util.StringUtils;
import org.springframework.http.HttpHeaders;

import javax.servlet.*;
import javax.servlet.FilterConfig;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * ChoviWu Created By 2018年4月16日13:29:01
 */
@WebFilter("sessionFilter")
public class SessionFilter implements Filter {

  private String key = "FSMKSMVISKIAID$23191293FEIWGJ1234!234FFAMKMPI";
  @Override
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest)req;
    HttpServletResponse response = (HttpServletResponse)res;
    addHeader(response);

    String path=request.getServletPath();
    //过滤链接
    //需登录的
    String[] noNeedLoginPaths={"/user/login","/static/","/login","/upload","/validate","/index","/favicon" };
    //需登录的
    String[] needLoginPaths={"/user","/account","/web","/invest","/forgetPassword"};

    boolean noNeedLogin=isMatch(path,noNeedLoginPaths);
    if(noNeedLogin){
      chain.doFilter(req,res);
    }else{
        //登陆
        boolean needLogin=isMatch(path,needLoginPaths);
        if(needLogin){
          //Jwt Token 跨域验证
          String token = request.getHeader("Access-Controll-Token");
          String result = null;
          if(StringUtils.isEmpty(token)){
            this.filter(response);
            return;
          }
          try {
            result = JwtUtil.verify(token,key);
          } catch (Exception e) {
            e.printStackTrace();
          }
          boolean flag = StringUtils.isEmpty(result)? false : true;
          if(!flag){
            this.filter(response);
            return;
          }
          chain.doFilter(request,response);
        }
    }
  }
  public void init(FilterConfig filterConfig) {}

  public void destroy() {}

  private boolean isMatch(String path, String[] paths){
    boolean isMatch = false;
    for(String p:paths){
      if(path.startsWith(p)){
        isMatch = true;
        break;
      }
    }
    return isMatch;
  }
  //请求头设置
  private void addHeader(HttpServletResponse response){
    response.addHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS,"GET,POST,DELETE,OPTION,OPTIONS,PUT");
    response.addHeader(HttpHeaders.ACCESS_CONTROL_MAX_AGE,"3600");
    response.addHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS,"true");
    //TOKEN 跨域
    response.addHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS,"Content-Type,Authorization," +
            "Token-Allow-User,x-requested-with");
    response.addHeader(HttpHeaders.ACCEPT_ENCODING,"UTF-8");
    response.addHeader(HttpHeaders.ACCEPT_LANGUAGE,"text/html,application/xhtml+xml,application/xml");
    response.addHeader("Server","nginx/1.3.0");
  }
  private void filter(HttpServletResponse response) throws IOException {
    Map msg = new HashMap();
    msg.put("result","fail");
    msg.put("messageCode", "403");
    msg.put("messageText", "session.timeout");
    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(msg);
    response.setContentType("application/json;charset=UTF-8");
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    PrintWriter out = response.getWriter();
    out.print(json);
    out.flush();
    out.close();
  }

}